package org.example.buysystem.service;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.buysystem.constants.Constants;
import org.example.buysystem.entity.Avatar;
import org.example.buysystem.exception.ServiceException;
import org.example.buysystem.mapper.AvatarMapper;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Service

public class AvatarService extends ServiceImpl<AvatarMapper, Avatar> {


    public void downloadAvatar(String fileName, HttpServletResponse response) {
        File file = new File(Constants.avatarFolderPath+fileName);
        if(!file.exists()){
            throw new ServiceException(Constants.CODE_500,"文件不存在");
        }
        try{
            ServletOutputStream outputStream = response.getOutputStream();
            response.addHeader("Content-Disposition","attachment;filename="+fileName);
            response.setContentType("application/octet-stream");
            outputStream.write(FileUtil.readBytes(file));
            outputStream.flush();
            outputStream.close();

        }catch (IOException e){

        }
    }
}

